import { GenericEnvStore } from "@/modules/dev-env/store/generic-env-store.ts";
import type { LocalVersionItem } from "@/modules/dev-env/common/types.ts";
import path from "@/framework/util/path.ts";
import type { BaseEnvMirror } from "@/modules/dev-env/mirror/mirror.ts";
import type { EnvTableAction } from "@/modules/dev-env/store/types.ts";
import { execInTerminal, openInTerminal } from "@/util/system-utils2.ts";
import { RocketmqMirror } from "@/modules/dev-env/middleware/rocketmq/rocketmq-mirror.ts";

export class RocketmqEnvStore extends GenericEnvStore<RocketmqEnvStore> {
  constructor() {
    super("rocketmq");
    this.icon = "icon-rocketmq";
    this.pageConfig = {
      showCurrentAction: false,
      showSetting: false,
    };
    this.tableActions = this._tableActions();
  }

  private _tableActions(): EnvTableAction[] {
    return [
      {
        key: "mqnamesrv",
        name: "mqnamesrv",
        icon: "icon-terminal",
        onClick: (version: LocalVersionItem) => this._execCmd(version, "mqnamesrv"),
      },
      {
        key: "open-in-terminal",
        name: "在终端打开",
        icon: "icon-terminal",
        onClick: (version: LocalVersionItem) => openInTerminal(version.installPath, { subPath: ["bin"], env: this._getEnv(version) }),
      },
    ];
  }

  private _getEnv(version: LocalVersionItem) {
    return {
      ROCKETMQ_HOME: version.installPath,
    };
  }

  private _execCmd(version: LocalVersionItem, cmd: string) {
    execInTerminal(cmd, { cwd: version.installPath, subPath: ["bin"], env: this._getEnv(version) });
  }

  protected getMirrors0(): BaseEnvMirror[] {
    return [
      new RocketmqMirror("aliyun"),
      new RocketmqMirror("tencent"),
      new RocketmqMirror("tsinghua"),
      new RocketmqMirror("apache"),
      // ...
    ];
  }

  protected async getVersionInfo(versionDir: string): Promise<LocalVersionItem | undefined> {
    // rocketmq-all-5.3.3-bin-release
    const folderName = path.basename(versionDir);
    if (!folderName.startsWith("rocketmq-all-")) return undefined;
    const runserver = path.join(versionDir, "bin/runserver.sh");
    if (!(await native.fs.exists(runserver))) return undefined;

    const [, , version] = folderName.split("-");
    return Promise.resolve({
      version: version,
      installPath: versionDir,
    });
  }
}
